<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/14
 * Time: 13:36
 *
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\admin\controller;

use app\common\model\Timing;
use app\Request;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;

class  Config{
    public function  index(){
        $configModel = new \app\common\model\Config();
        $configList = $configModel->select()->toArray();
        $configList = array_column($configList, 'value', 'key');
        return success('配置', $configList);
    }

    public function edit(Request $request){
        $param = $request->param();
        $configModel = new   \app\common\model\Config();
        foreach ($param as $key => $value) {
            $configModel->where(['key' => $key])->update(['value' => trim($value)]);
        }
        return success('修改成功');
    }

    public function upload(Request $request)
    {
        $configModel = new \app\common\model\Config();
        $value = $configModel::getConfigValue('upload_way');
        $files = $request->file("file");
        if (!$files) {
            return error('请上传文件');
        }
        $ext = $files->extension();

        $size = filesize($files);
        if ($value == 1 || $ext == 'pem') {
            try {
                if ($ext == 'pem'){
                    $tempFile = $_FILES['file']['tmp_name'];
                    $targetFile = './uploads/' . date('YmdHis').$_FILES['file']['name'];
                    if (move_uploaded_file($tempFile, $targetFile)) {
                        return success('上传成功', ['url' => $targetFile]);
                    } else {
                        return error('上传失败');
                    }
                }else{
                    $path = 'uploads';
                    // 将图片保存至本地
                    $saveName = Filesystem::disk('public')->putFile($path, $files);
                    $saveName = $request->domain() . '/storage/' . $saveName;
                    return success('上传成功', ['url' => $saveName]);
                }

                //将文件上传的路径返回
            } catch (\think\exception\ValidateException $e) {
                return error($e->getMessage());
            }
        } else if ($value == 2) {
            $fileType = $configModel::getConfigValue('qiniu_file_type');
            if ($fileType) {
                $fileTypeArray = explode(',', $fileType);
                if (!in_array($ext, $fileTypeArray)) {
                    return error('此类型文件不允许上传');
                }
            }
            $qiniu_access_key = $configModel::getConfigValue('qiniu_access_key');
            $qiuniu_secret_bucket = $configModel::getConfigValue('qiniu_secret_key');
            $qiniu_bucket = $configModel::getConfigValue('qiniu_bucket');

            // 构建Auth对象
            $auth = new Auth($qiniu_access_key, $qiuniu_secret_bucket);

            // 要上传的空间
            $bucket = $qiniu_bucket;
            // 生成上传Token
            $token = $auth->uploadToken($bucket);

            // 上传到七牛后的文件名
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();

            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $files->getRealPath());
            if ($err !== null) {
                error('上传失败');
            } else {
                return success('上传成功', ['url' => $configModel::getConfigValue('qiniu_domin') . '/' . $ret['key']]);
            }
        } else {
            $fileType = $configModel::getConfigValue('ali_file_type');
            $fileTypeArray = explode(',', $fileType);
            if (!in_array($ext, $fileTypeArray)) {
                return error('此类型文件不允许上传');
            }
            $accessKeyId = $configModel::getConfigValue('ali_access_key');
            $accessKeySecret = $configModel::getConfigValue('ali_secret_key');
            $endpoint = $configModel::getConfigValue('ali_domain');
            $bucket = $configModel::getConfigValue('ali_bucket');
            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            //这里是有sha1加密 生成文件名 之后连接上后缀
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();
            //上传至阿里云的目录 为年+月/日的格式
            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $key, $files->getRealPath());

            //将结果输出
            return success('上传成功', ['url' => $result['info']['url']]);

        }
    }
    public function Timing(){
        $TimingModel  = new Timing();
        $data =  $TimingModel->select()->toArray();
        $count =  $TimingModel->count();

        $dir  =   $sql = str_replace("/public", "", $_SERVER['DOCUMENT_ROOT'] );
        foreach ($data as $key =>  $value){
            $data[$key]['link'] ='php'.  $dir.$value['link'];
        }
        return success('',['list'=>$data,'count'=>$count ]);
    }
}
